package com.hhq.redistest.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/8/15 19:03
 */
@RestController
@Slf4j
public class TestApi {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public final static String MODIFY_PREFIX = "modify:";
    private static final int MAX_SIZE = 5;

    // 将元素添加到 List 的尾部
    public void addElement(String userId, String password) {
        String key = MODIFY_PREFIX + userId;
        // 将新元素添加到 List 的尾部
        redisTemplate.opsForList().rightPush(key, password);

        // 获取 List 的长度
        Long size = redisTemplate.opsForList().size(key);
        if (size != null && size > MAX_SIZE) {
            // 修剪 List，只保留最新的 MAX_SIZE 个元素
            redisTemplate.opsForList().trim(key, size - MAX_SIZE, -1);
        }
    }

    // 获取 List 中的所有元素
    public List<Object> getAllElements(String userId) {
        String key = MODIFY_PREFIX + userId;
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    private boolean checkPassword(String userId, String password) {
        List<Object> passwords = getAllElements(userId);
        if (CollectionUtils.isEmpty(passwords)) {
            return true;
        }
        List<String> list = passwords.stream().map(item -> item.toString()).collect(Collectors.toList());
        if (list.contains(password)) {
            return false;
        } else {
            return true;
        }
    }

    @GetMapping("/add")
    public String add(@RequestParam("userId") String userId, @RequestParam("password") String password) {
        addElement(userId, password);
        return "success";
    }

    @GetMapping("/test")
    public Boolean test(@RequestParam("userId") String userId, @RequestParam("password") String password) {
        return checkPassword(userId, password);
    }
}
